package com.dede.mypermission

import android.app.Fragment
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.util.Log


/**
 * @author hsh
 * @date 2017/8/22 10:43.
 * @doc
 */
class MyPermissionFragment : Fragment() {

    val permissionApi = PermissionRequestImpl(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (permissionApi.requestCode != requestCode) return

        permissions.forEachIndexed { index, permission ->
            val shouldShowRequestPermissionRationale = shouldShowRequestPermissionRationale(permission)
            val grantResult = grantResults[index]

            val permissionInfo = Permission()
            permissionInfo.isGrantResult = grantResult == PackageManager.PERMISSION_GRANTED
            permissionInfo.isShouldShowRequestPermissionRationale = shouldShowRequestPermissionRationale
            permissionInfo.permission = permission
            permissionInfo.requestCode = requestCode

            when (grantResult) {
                PackageManager.PERMISSION_GRANTED -> {
                    permissionApi.granted(permissionInfo)
                }
                PackageManager.PERMISSION_DENIED -> {
                    permissionApi.denied(permissionInfo)
                }
                else -> {
                    Log.e("MyPermissionFragment", "onRequestPermissionsResult: UnKnow grantResult!")
                }
            }
        }
    }

}